<template>
  <common-search :show-item="2" :col-layout="{xxl: 6, xl:8, lg: 8, md: 12, sm: 24, xs: 24}" v-model="query" :formItems="formItems" @search="onSearch" @reset="onReset"></common-search>
<!--  <a-button type="primary" @click="test" :loading="syncLoading">测试</a-button>-->
  <a-button type="primary" v-modulePerm="['truckDeliver:loadingSync']" @click="sync" :loading="syncLoading">待发同步</a-button>
  <a-button style="margin-left: 10px;" type="primary" v-modulePerm="['truckDeliver:singleImport']" @click="$router.push('/tail/singleImport')">单条导入</a-button>
  <a-button style="margin-left: 10px;" type="primary" v-modulePerm="['truckDeliver:mulImport']" @click="imports">批量导入</a-button>
  <a-dropdown>
    <template #overlay>
      <a-menu @click="handleMenuClick">
        <a-menu-item :key="item.code" v-for="(item,index) in batchList ">
          {{item.label}}
        </a-menu-item>
      </a-menu>
    </template>
    <a-button v-modulePerm="['truckDeliver:sync']" type="primary" style="margin-left: 10px">
      批量下单
      <DownOutlined />
    </a-button>
  </a-dropdown>
  <a-button style="margin-left: 10px;"  type="primary" @click="exports" :loading="exportLoading" v-modulePerm="['truckDeliver:export']">
    <template #icon>
      <ExportOutlined />
    </template>
    选择导出
  </a-button>
  <my-alert @onClearSelected="onClearSelected" :selectedRowKeys="selectedRowKeys" style="margin-top: 10px;"></my-alert>
  <common-table
      :customFilterDropdown="true"
      :columns="columns"
      :dataSource="dataList"
      v-model:localPagination="page"
      @paginationChange="pageChange"
      v-model:loading="loading"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      :rowKey="(record) => record.id"
      :scroll="{ x: 'max-content'}"
      :slots="['action','rateAbstractList','status']"
  >
    <template #status="{ record }">
      <span :style="{color: statusColor[record.status]}">{{statusStr[record.status]}}</span>
    </template>
    <template #rateAbstractList="{ record }">
      <div v-for="(item,index) in record.rateAbstractList">
        {{ index + 1 }}.{{ item.platform }} / {{ item.carrierCode }} : {{ item.totalCharge }}
        <template v-if="item.totalCharge"> ({{ ((item.totalCharge / record.priceValue) * 100).toFixed(2) }} %)</template>
      </div>
    </template>
    <template #action="{ record }">
      <a-dropdown trigger="click">
        <a class="ant-dropdown-link" @click="handleVisibleChange(record)">
          更多
          <DownOutlined />
        </a>
        <template #overlay>
           <a-menu>
             <a-menu-item v-if="['NONE'].includes(record.status) && modulePerm(['truckDeliver:ask'])">
               <a @click="$router.push({path:'/tail/truckDeliver/form',query:{id:record.id}})">询价</a>
             </a-menu-item>
             <a-menu-item v-if="['NONE'].includes(record.status) && modulePerm(['truckDeliver:del'])">
               <a-popconfirm title="确定要作废吗？" ok-text="确定" cancel-text="取消" @confirm="confirmDel(record)">
                 <a>作废</a>
               </a-popconfirm>
             </a-menu-item>
             <a-menu-item v-if="['RATED', 'TAGGED'].includes(record.status) && modulePerm(['truckDeliver:compare'])">
               <a  @click="$router.push({path:'/tail/truckDeliver/detail',query:{id:record.id}})">比价</a>
             </a-menu-item>
             <a-menu-item v-if="['RATED', 'TAGGED'].includes(record.status) && modulePerm(['truckDeliver:del'])">
               <a-popconfirm title="确定要作废吗？" ok-text="确定" cancel-text="取消" @confirm="confirmDel(record)">
                 <a>作废</a>
               </a-popconfirm>
             </a-menu-item>
             <a-menu-item v-if="['ORDERED', 'CANCELLED'].includes(record.status) && modulePerm(['truckDeliver:detail'])">
               <a @click="$router.push({path:'/tail/truckDeliver/detail',query:{id:record.id}})">详情</a>
             </a-menu-item>
             <a-menu-item :disabled="!record.isBack" v-if="modulePerm(['truckDeliver:back'])">
                 <a-spin :spinning="record.loading">
                   <a-popconfirm title="确定要回退吗？" ok-text="确定" cancel-text="取消" @confirm="back(record)">
                    <span>回退</span>
                  </a-popconfirm>
                 </a-spin>

             </a-menu-item>
           </a-menu>
        </template>
      </a-dropdown>
    </template>

  </common-table>
  <upload-file :type="'upload'" :url="'/api/wms/truck/import'" :method="'post'" :title="'导入'" ref="upFile" :name="'批量上传'" @search="search">
    <template #template>
      <a @click="downLoadTemplate">下载模版</a>
    </template>
  </upload-file>
</template>
<script>
export default {
  name:"tail-truckDeliver"
}
</script>
<script setup>
import CommonSearch from "@/components/commonSearch/index.vue";
import CommonTable from "@/components/commonTable/index.vue";
import {useSearchTable} from "@/hooks/table/useSearchTable";
import {ref, onMounted} from "vue";
import {message} from "ant-design-vue";
import {postFile} from "@utils/service/index.js";
import MyAlert from "@/components/alert/my-alert.vue";
import {
  batchBooking,
  batchBookingStrategyList,
  cancelOrder, createByPendingOrder,
  createByPendingOrderLoop, getBatchBookingStatus,
  getTruckDeliverList, isReturnTruckStatus, returnTruckStatus
} from "@/api/tail/truckDeliver.js";
import {modulePerm} from "@utils/modulePerm.js";
const { dataList, query, loading, page, search, reset, onPageChange } = useSearchTable({
  searchAPI: getTruckDeliverList,
  queryFactory: () => ({
  }),
  beforeSearch:() => {
    if(query.value.time){
      query.value.orderTimeBegin = query.value.time[0]
      query.value.orderTimeEnd = query.value.time[1]
    }else{
      delete query.value.orderTimeEnd
      delete query.value.orderTimeEnd
    }
  },
  afterSearch:() => {
    dataList.value.forEach(item => {
      item.isBack = false
      item.loading = false
    })
  }
});
const imports = async () => {
  upFile.value.handleShow()
}
const back = async (record) => {
  try {
    const res = await returnTruckStatus({saleOrderCode:record.saleOrderCode})
    message.success('回退成功')
  }catch (e){
    message.error(e)
  }
}
const downLoadTemplate = async () => {
  try{
    const res = await postFile('/api/wms/truck/download/import/template','post',{},'卡派订单模板.xlsx')
  }catch (e) {
    message.error(e)
  }
}
let timer
let timer1
const upFile = ref()
const batchList = ref([])
const statusStr = {
  NONE: '未处理',
  RATED: '已询价',
  ORDERED: '已下单',
  TAGGED: '已标记',
  CANCELLED: '已取消'
}
const statusColor = {
  RATED: '#17A2B8',
  ORDERED: '#28A745',
  CANCELLED: '#DC3545'
}
const columns = ref([
  {
    title: '平台订单',
    align: 'center',
    dataIndex: 'userOrderId'
  },
  {
    title: '易仓订单',
    align: 'center',
    dataIndex: 'saleOrderCode',
  },
  {
    // 状态：NONE-未处理, RATED-已询价, ORDERED-已下单, CANCELED-取消
    title: '状态',
    align: 'center',
    dataIndex: 'status',
  },
  {
    title: '跟踪号',
    align: 'center',
    dataIndex: 'rateOrderId'
  },
  {
    title: '提货日期',
    align: 'center',
    dataIndex: 'originDate'
  },
  {
    title: '服务等级',
    align: 'center',
    dataIndex: 'specialService'
  },
  {
    title: '提货仓库',
    align: 'center',
    dataIndex: 'originWarehouse'
  },
  {
    title: '提货号',
    align: 'center',
    dataIndex: 'serviceBillCode'
  },
  {
    title: '承运商',
    align: 'center',
    dataIndex: 'carrierName',
  },
  {
    title: '运费',
    align: 'center',
    dataIndex: 'totalCharge'
  },
  {
    title: '比价',
    align: 'left',
    dataIndex: 'rateAbstractList',
  },
  {
    title: '商品',
    align: 'center',
    dataIndex: 'goodsSkus'
  },
  {
    title: '处理人',
    align: 'center',
    dataIndex: 'opUser'
  },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
  }
])
const formItems = ref([
  {
    label:'平台订单',
    type:'input',
    field:'userOrderId',
  },
  {
    label:'易仓订单',
    type:'input',
    field:'saleOrderCode',
  },
  {
    label:"跟踪号",
    type:'input',
    field: 'rateOrderId',

  },
  {
    label:'承运商',
    type:'input',
    field:'carrierCode',
  },
  {
    label:"状态",
    type:'select',
    field: 'status',
    options:Object.keys(statusStr).map(key => {
      return {
        label:statusStr[key],
        value:key
      }
    })
  },
  {
    label:'特殊服务',
    type:'select',
    field:'specialService',
    options: [
      {
        label:'OD',
        value:'OD'
      },
      {
        label:'IDD',
        value:'IDD'
      },
      {
        label:'WGD',
        value:'WGD'
      },
      {
        label:'ASSY',
        value:'ASSY'
      },
    ]
  },
  {
    label:'卡派下单日期',
    showTime:true,
    type:'rangePicker',
    field: 'time'
  },
  {
    label:'仓库',
    field:'originWarehouse',
    type:'input'
  }
])
const syncLoading = ref(false)
const selectedRowKeys = ref([])
const onSelectChange = (e) => {
  console.log(e)
  selectedRowKeys.value = e
}
const handleVisibleChange = async (record) => {
  try{
    console.log(record)
    record.loading = true
    const res = await isReturnTruckStatus({saleOrderCode:record.saleOrderCode})
    record.isBack = res.result
  }catch (e){
    message.error(e)
  }finally {
    record.loading = false
  }
}

const sync = async () => {
  try{
    syncLoading.value = true
    const res1 = await createByPendingOrderLoop()
    timer = setInterval(async () => {
      try{
        const res1 = await createByPendingOrderLoop()
        syncLoading.value = false
        message.success('同步完成')
        clearInterval(timer)
      }catch (e) {}
    },30000)
    const res = await createByPendingOrder()
    console.log(res)
    message.success(res.message)
  }catch (e) {
    message.error(e)
  }
}

const pageChange = () => {
  selectedRowKeys.value = []
  onPageChange()
}

const onSearch = () => {
  selectedRowKeys.value = []
  search()
}

const onReset = () => {
  selectedRowKeys.value = []
  reset()
}

const exportLoading = ref(false);
/**
 * 导出订单
 * @returns {MessageType}
 */
const exports = async () => {
  try{
    exportLoading.value = true;
    let obj = { ...query.value }
    if(selectedRowKeys.value.length <= 0){
      return message.error('请选择要导出的订单')
    }
    obj.truckOrderIds = [...selectedRowKeys.value]
    const res = await postFile('/api/wms/truck/order/downloadExcel','post',obj,'卡派下单.xlsx')
    message.success('导出成功')
  }catch (e) {
    message.error(e);
  }finally {
    exportLoading.value = false;
  }
}

/**
 *
 * @param e
 * @returns {Promise<""|"success"|"warning"|"info"|"error">}
 */
const handleMenuClick = async (e) => {
  try {
    if (selectedRowKeys.value.length > 0) {
      const valid = await getBatchBookingStatus({})
      console.log(valid)
      const res = await batchBooking({
        strategy: e.key,
        idList: selectedRowKeys.value
      })
      message.success(res.message)
      selectedRowKeys.value = []
    }else {
     return message.error('你还未勾选选项')
    }
  }catch (e){
    message.error(e)
    if(e === '批量下单处理中'){
      clearInterval(timer1)
      timer1 = setInterval(async () => {
        try{
          const valid = await getBatchBookingStatus({})
          clearInterval(timer1)
        }catch (e) {
          search()
        }
      },10000)
    }
  }
}


const init = async () => {
  try{
    const res = await batchBookingStrategyList()
    batchList.value = res.result.records
  } catch (e){
    message.error(e)
  }
}

/**
 * 作废订单
 * @param record
 * @returns {Promise<void>}
 */
const confirmDel = async (record) => {
  try{
    const res = await cancelOrder({
      id: record.id,
      userOrderId: record.userOrderId,
    })
    message.success('作废成功')
    await search()
  }catch (e){
    message.error(e)
  }
}

const onClearSelected = () => {
  selectedRowKeys.value = []
}

onMounted(()=>{
  init()
})

</script>
<style scoped>

</style>
